param (
		[string]$CMSiteName = $(throw "$CMSiteName is a required parameter"),
		[string]$CDServerName = $(throw "$CDServerName is a required parameter"),
		[string]$CDSiteName = $(throw "$CDSiteName is a required parameter")
)

# Be quiet!

$WarningPreference = "SilentlyContinue" 
$ErrorActionPreference = "SilentlyContinue" 

#
#	Main
#	====
#
#	This script copy SwitchMasterToWeb and update ConnectionStrings.config on the DC server
#

Write-Host "`n`n----> Updating ConnectionStrings.config on the current server`n`n" -foregroundcolor Yellow

$CMConnectionStrings = "C:\inetpub\wwwroot\" + $CMSiteName + "\Website\App_Config\ConnectionStrings.config"

$xmlCM = [xml](Get-Content $CMConnectionStrings)

if (-not $?)
{
	Write-Host "     - Error opening ConnectionString.config on CM Server!`n`n" -ForegroundColor Red
	exit
}

$xmlCM.connectionStrings.add | foreach {   if ($_.Name -eq "web") { $_.connectionString = $_.connectionString -replace $CMSiteName, $CDSiteName }   }
$xmlCM.Save($CMConnectionStrings)

#--- copies the SwitchMasterToWeb

Write-Host "----> Copying SwitchMasterToWeb.config to the DC server`n`n" -foregroundcolor Yellow

$CD_MACHINE = [System.Net.Dns]::GetHostByName(($CDServerName))

$source = Split-Path (Resolve-Path $MyInvocation.MyCommand.Path)
$source = $source + "\SwitchMasterToWeb.config"
$destination = "\\" + $CD_MACHINE.HostName + "\c$\inetpub\wwwroot\" + $CDSiteName  +  "\Website\App_Config\include"

copy-item -Path $source -Destination $destination

if (-not $?)
{
	Write-Host "     - Error copying SwitchMasterToWeb to CD Server!`n`n" -ForegroundColor Red
	exit
}


#--- updates ConnectionStrings.config

Write-Host "----> Updating ConnectionStrings.config on the DC server`n`n" -foregroundcolor Yellow

$destination = "\\" + $CD_MACHINE.HostName + "\c$\inetpub\wwwroot\" + $CDSiteName  +  "\Website\App_Config\ConnectionStrings.config"

$xmlCD = [xml](Get-Content $destination)

if (-not $?)
{
	Write-Host "     - Error while trying to update ConnectionStrings.config on CD Server!`n`n" -ForegroundColor Red
	exit
}

$nodesCD = $xmlCD.SelectNodes("//add")

foreach($nodeCD in $nodesCD) 
{
	if ($nodeCD.name -eq "master")
	{
		$nodeCD.ParentNode.InnerXml = $nodeCD.ParentNode.InnerXml.Replace($nodeCD.OuterXml, $nodeCD.OuterXml.Insert(0, "<!--").Insert($nodeCD.OuterXml.Length + 4, "-->"))
	}	
}

$xmlCD.Save($destination)


#--- SCRIPT COMPLETION

Write-Host "----> Done!`n`n" -foregroundcolor Yellow